package k8.buffer.vbo;

import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.IntBuffer;

import k8.buffer.VerticesBuffer;

import org.lwjgl.opengl.GL11;
import org.lwjgl.opengl.ARBVertexBufferObject;


public final class VBOVerticesBuffer extends VerticesBuffer {
    
	private int id;
	
    /**
     * Creates an instance of VBOVerticesBuffer.
     * 
     * @param initialcapacity
     *          Initial capacity (number of vertices)
     */
    public VBOVerticesBuffer(int initialcapacity) {
        super(initialcapacity);
        IntBuffer int_buffer = ByteBuffer.allocateDirect(4).order(ByteOrder.nativeOrder()).asIntBuffer();
        ARBVertexBufferObject.glGenBuffersARB(int_buffer);
        id = int_buffer.get(0);
    }

    @Override
    public void destroy() {
        IntBuffer int_buffer = ByteBuffer.allocateDirect(4).order(ByteOrder.nativeOrder()).asIntBuffer();
        int_buffer.put(id);
        ARBVertexBufferObject.glDeleteBuffersARB(int_buffer);
    }
    
    @Override
    public void glVertexPointer() {
    	ARBVertexBufferObject.glBindBufferARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, id);
    	if ( flush ) {
    		buffer.rewind();
            ARBVertexBufferObject.glBufferDataARB(ARBVertexBufferObject.GL_ARRAY_BUFFER_ARB, buffer, ARBVertexBufferObject.GL_STATIC_DRAW_ARB);
            flush = false;
    	}
        GL11.glVertexPointer(3, GL11.GL_FLOAT, 0, 0);
    }
    
}
